using Aurora.Security.MD5;
using Gateway.Common.Models;
using Gateway.IQuery.Sign;
using Gateway.IQuery.Sign.Request;
using Gateway.IQuery.Sign.Result;
using Gateway.IRepositories;

namespace Gateway.Query;

/// <summary>
/// 
/// </summary>
public class SignQuery : ISignQuery
{
    private readonly IQueryRepository _repository;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="repository"></param>
    public SignQuery(IQueryRepository repository)
    {
        _repository = repository;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    /// <exception cref="MyException"></exception>
    public async Task<LoginResult> Sign(LoginPasswordRequest request)
    {
        var sql =
            @"select userid, useravatar, username, account, userno, roleids, departmentid from  User where Account=@account and Password=@password and Deleted='N' and Disabled='N'";
        request.Password = request.Password.ToMD5String();
        var data = await _repository.QueryFirstOrDefaultAsync<UserSignDetailResult>(sql, request);
        if (data == null)
            throw new MyException("账号或密码错误");
        var result = new LoginResult()
        {
            UserInfo = new LoginUserInfoResult()
            {
                RoleIds = data.RoleIds, UserId = data.UserId, UserName = data.UserName,
                Account = request.Account
            }
        };

        return result;
    }
}